<?php
namespace Admin\Controller;
use Think\Controller;
use Think\Log;
class SpecialofferController extends BaseController {
	
     public function index(){
		$this->display();
	}

    
    public function specialOfferList()
    { 
  	    $_listrows = I('request.verypageshowcount', '', 'trim');  
		$keywords = I('request.keywords','','trim');
		if(!empty($keywords)){
			$_where['parcelname']=array('like',"%{$keywords}%");
		} 
	    $where_order['where'] = $_where; 
		$where_order['listrows'] = $_listrows;
		$where_order["id"]="load_tb_div";
		$where_order["alias"]="a";
		$where_order["order"]="a.createtime desc";
        $where_order["field"]="a.*,u.user_name";
        $where_order["join"]=array("inner join ".$this->dbprefix."admin_user u on a.operationuser=u.user_id"); 

		$_datalist = $this->_getListsFromModel('wx_parcelbase', $where_order);
	

		$this->assign('_datalist', $_datalist);
		$this->display('select_wx_parcellist'); 
 

    }

 public function  add_special_offer(){
 	$this->display();
 }
//添加包裹
    public function addSpecialOffer(){
       $data['pb_id'] = guid() ;
       $data['parcelname'] =I('post.username');
       $data['isactive'] =I('post.in_or_out');
       $data['number'] = I('post.money');
       $data['operationuser'] = $_SESSION['admin_id'];
       $data['createtime'] = date('Y-m-d H:i:s');
       $res = D('wx_parcelbase')->add($data);
      	  $exe_scriptstr = "<script>
        setTimeout(function(){
			var win=    art.dialog.opener;
                        win._reload_currentpage_datalist('load_tb_div');
                        art.dialog.close();
        },500);
       </script>";
       if($res != false){
            //添加成功后，输出文本，把js脚本一起输出，前台只要html到某个div里就能够执行js
            $this->success('操作成功！' . $exe_scriptstr);
       }else{


       	   $this->success('操作失败！' . $exe_scriptstr);
       }
    	$this->display();
    }
//编辑特价
    public function update_special_offer(){
       $map['pb_id'] = I('get.pb_id');
       $list = D('wx_parcelbase')->where($map)->find();

       if($list != flase){
       	$this->assign('list',$list);
       	$this->display('update_special_offer');
       }

    }

    public function saveSpecialOffer(){
        $map['pb_id'] = I('post.oldid');
	       $data['parcelname'] =I('post.username');
	       $data['isactive'] =I('post.in_or_out');
	       $data['number'] = I('post.money');
	       $data['operationuser'] = $_SESSION['admin_id'];
           $data['createtime'] = date('Y-m-d H:i:s');
	       $res = D('wx_parcelbase')->where($map)->save($data);
	       	     $exe_scriptstr = "<script>
	                setTimeout(function(){
						var win=    art.dialog.opener;
	                                win._reload_currentpage_datalist('load_tb_div');
	                                art.dialog.close();
	                },300);
	                
	           </script>";
	       if($res != flase){
            
	            //添加成功后，输出文本，把js脚本一起输出，前台只要html到某个div里就能够执行js
	            $this->success('操作成功！' . $exe_scriptstr);
	        }else{
	       	
	            //添加成功后，输出文本，把js脚本一起输出，前台只要html到某个div里就能够执行js
	            $this->error('修改失败！' . $exe_scriptstr);	
	        }
           $this->display();
    }

    public function deleteSpecialOffer(){
     if(IS_GET){
        $map['pb_id'] = I('get.id');
        $row = D('wx_parcelbase')->where($map)->delete();
        if($row != flase){
        	$this->success("删除成功") ;
        }else{
        	$this->error("删除失败") ;
        }

     }


    }







//包邮价主表
    public function wx_parcel(){
       $this->display(); 
    }
    
    public function wx_parcel_tit_list(){
     	$_listrows = I('request.verypageshowcount', '', 'trim'); 
	   	//$_where['transaction_type'] = 1;
		
	 
		$keywords = I('request.keywords','','trim');
		if(!empty($keywords)){
			$_where['parcename']=array('like',"%{$keywords}%");
		}
	    $where_order['where'] = $_where; 
		$where_order['listrows'] = $_listrows;
		$where_order["id"]="load_tb_div";
		$where_order["alias"]="a";
		$where_order["order"]="a.createtime desc";
        $where_order["field"]="a.*,u.user_name";
        $where_order["join"]=array("inner join ".$this->dbprefix."admin_user u on a.operationuser=u.user_id"); 

		$_datalist = $this->_getListsFromModel('wx_parcel', $where_order);
	

		$this->assign('_datalist', $_datalist);
		$this->display('wx_parcel_tit_list'); 

    }
      
    public function add_wx_parcel(){
         $this->display();  
    }
    
    public function addWxParcel(){
       $data['parcelid'] = guid() ;
       $data['parcename'] =I('post.username');
       $data['isactive'] =I('post.in_or_out');
       $data['operationuser'] = $_SESSION['admin_id'];
       $data['createtime'] = date('Y-m-d H:i:s');
       $exe_scriptstr = "<script>
        setTimeout(function(){
			var win=    art.dialog.opener;
                        win._reload_currentpage_datalist('load_tb_div');
                        art.dialog.close();
        },500);
       </script>";
   	  if(I('post.in_or_out') == 1){
       	$s['isactive'] = 0 ;
       	 $result = D('wx_parcel')->where('1=1')->save($s);

       }
       $res = D('wx_parcel')->add($data);

       if($res != false){
            //添加成功后，输出文本，把js脚本一起输出，前台只要html到某个div里就能够执行js
            $this->success('操作成功！' . $exe_scriptstr);
       }else{


       	   $this->success('操作失败！' . $exe_scriptstr);
       }
    	$this->display();

    }

    public function update_wx_parcel(){
        $map['parcelid'] = I('get.parcelid');
       $list = D('wx_parcel')->where($map)->find();

       if($list != flase){
       	$this->assign('list',$list);
       	$this->display('update_wx_parcel');
       }
    }
    
    public function save_wx_parcel(){
        $map['parcelid'] = I('post.oldid');
	       $data['parcename'] =I('post.username');
	       $data['isactive'] =I('post.in_or_out');
	       $data['operationuser'] = $_SESSION['admin_id'];
           $data['createtime'] = date('Y-m-d H:i:s');
	        $exe_scriptstr = "<script>
	                setTimeout(function(){
						var win=    art.dialog.opener;
	                                win._reload_currentpage_datalist('load_tb_div');
	                                art.dialog.close();
	                },1000);
	                
	           </script>";
	       if(I('post.in_or_out') == 1){

	       	$s['isactive'] = 0 ;
	       	 $result = D('wx_parcel')->where('1=1')->save($s);
	       }
	       $res = D('wx_parcel')->where($map)->save($data);
	       	    
	       if($res != flase){
            
	            //添加成功后，输出文本，把js脚本一起输出，前台只要html到某个div里就能够执行js
	            $this->success('操作成功！' . $exe_scriptstr);
	        }else{
	       	
	            //添加成功后，输出文本，把js脚本一起输出，前台只要html到某个div里就能够执行js
	            $this->error('操作失败！' . $exe_scriptstr);	
	        }
           $this->display();
    }
       public function delete_wx_parcel(){
	     if(IS_GET){
	        $map['parcelid'] = I('get.id');
	        $row = D('wx_parcel')->where($map)->delete();
	        if($row != flase){
	        	$this->success("删除成功") ;
	        }else{
	        	$this->error("删除失败") ;
	        }

	     }

    }







    //包邮价格从表

    public function wx_parcellist(){
    	$list = D('wx_parcel')->field('parcelid,parcename')->select();
    	if($list != false){
    		$this->assign('list' ,$list);
           $this->display();
    	}
 

    }
	 
	 public function select_wx_parcellist(){

  	     $_listrows = I('request.verypageshowcount', '', 'trim'); 
		 $keywords = I('request.keywords','','trim');
		 $parcelid = I('request.parcelid');

		if( $parcelid != -1 && !empty($parcelid)){
			$_where['a.parcelid']=$parcelid;
		}

		if(!empty($keywords)){
			$_where['goodsname|parcename']=array('like',"%{$keywords}%");
		}
		
		 
		$where_order['where'] = $_where; 
		$where_order['listrows'] = $_listrows;
		$where_order["id"]="load_tb_div";
        $where_order["field"]="a.*,c.parcename,u.user_name";
        $where_order['alias']="a";
        $where_order["join"] =array(' inner join '.$this->dbprefix.'wx_parcel c on a.parcelid=c.parcelid',' inner join '.$this->dbprefix.'admin_user u on a.operationuser=u.user_id'); 
        $where_order["order"]="a.createtime desc";
        
		$_datalist = $this->_getListsFromModel('wx_parcellist', $where_order);
		$this->assign('_datalist', $_datalist);
		$this->display('special_offer_list'); 
  
	 }

    public function add_wx_parcellist(){ 
    	$id=I("parcelid");		
		$id= isset($id)?$id:'';
		$id =empty($id)?'':$id; 
        $this->assign('id',$id);
        $this->display('add_wx_parcellist');
    }
  //选择商品
    public function selection_of_goods(){ 
        	$this->display(); 
    }

    public  function selection_of_goods_list(){
        $id=I("post.id");		
		$id= isset($id)?$id:'';
		$id =empty($id)?'':$id; 
       $sort=M("wx_parcel")->field("parcelid,parcename")->select(); 
		$this->assign ( "parcel", $sort ); 
       $parcelbase=M("wx_parcelbase")->field("pb_id,parcelname,number")->where('isactive = 1')->select(); 
	    $this->assign( "parcelbase", json_encode($parcelbase));


       $ls=M("wx_parcellist")->alias("a")->field("a.*,c.parcelname,c.number")->join(" left join ".$this->dbprefix."wx_parcelbase c on a.pb_id=c.pb_id")->where("a.parcelid='$id'")->order("a.createtime desc")->select();
       $this->assign('purchaselist',$ls);
       $this->assign("parcelid",$id);
       $this->display();
     

    }

 public function  goods_list(){
 	    $_listrows = I('request._listrows', '', 'trim');
		$keywords = I('request.keywords','','trim');
		if(!empty($keywords)){
		   $_where['goods_name|goods_sn|goods_id']=array('like',"%{$keywords}%");
		} 
		$_where['is_general']=1;
		$where_order['where'] = $_where;
		$where_order['listrows'] = $_listrows;
		$where_order["id"]="load_tb_div"; 
		$where_order["field"]="a.*,CASE WHEN c.measure_unit='' THEN '千克' ELSE measure_unit END AS measure_unit,REPLACE(a.goods_name,'\'','’') AS goods_name";
		$where_order['alias']="a";
		$where_order["join"] =array(' INNER JOIN `'.$this->dbprefix.'category` c ON a.cat_id=c.cat_id');
		$where_order['order']="a.goods_id desc";
		
        $_datalist = $this->_getListsFromModel('Goods', $where_order);
      	$this->assign('_datalist', $_datalist);
		$this->display('goods_list');
 }

    public function update_wx_parcellist(){
		$ret=array('staute'=>'error','msg'=>"保存失败");
		$parcel=I("parcel");
		$postdata=I("json");
		
		if(empty($parcel)||empty($postdata)){
			$ret=array('staute'=>'error','msg'=>"传输参数错误");
			$this->ajaxReturn ($ret);
			exit;
		} 
		
		$json = json_decode($postdata,true); 
		if(!is_array($json)){
			$ret=array('staute'=>'error','msg'=>"特价商品信息错误");
			$this->ajaxReturn ($ret);
			exit;
		}
		//对数据进行处理
		 $sl=M("wx_parcellist");
		 $where['parcelid'] = $parcel;
		 $dblist= $sl->where($where)->select(); //数据库当前主题存在的记录信息;
		 
		 $aryadd=$arydel=$aryupd=array();
		 //提交数据 是否在数据库中存在，存在更新否则增加
		 foreach($json as $k=>$v){ 
		 	$flg=0;
		 	foreach ($dblist as $key=>$o){ 
		 	  if($v["listid"]==$o['listid'] && $v["parcelid"]==$o['parcelid'] && $v["pb_id"]==$o['pb_id'] && $v["goodsid"]==$o['goodsid']){
		 	  	  $aryupd[]=$v;		
		 	  	  $flg=1;
		 	  	  break;
		 	  }
		 	}
		   if($flg==0){
		   	    $v["listid"]=$listid;
		     	$aryadd[]=$v;
		   }
		 }
		 
		 //在数据库里存在，但是提交的数据不存在，删除数据
		 foreach ($dblist as $key=>$o){
		 	$bl=0;
		 	foreach($json as $k=>$v){
		 	  if($v["listid"]==$o['listid'] && $v["parcelid"]==$o['parcelid'] && $v["pb_id"]==$o['pb_id'] && $v["goodsid"]==$o['goodsid']){ 
		 			$bl=1;
		 			break;
		 		}
		 	}
		 	if($bl==0){
		 		$arydel[]=$o;
		 	}
		 }
		  
		 $sqladd=$sqlupd=$sqldel="";
		 $arysqlupd=array();  
		 $time=date("Y-m-d H:i:s");
		 

 
		 //构建插入数据语句
		 if(count($aryadd)>0){
		 	$sqlval=""; 
		 	foreach ($aryadd as $k=>$v){
		 		$listid=getGuid();//创建guid值
		 		$money = intval($v['number'])*$v['price'] + $v['logistics_price']*$v['weight'];
		 		$sqlval.=((empty($sqlval)?"":",")."('$listid','$parcel','".$v['pb_id']."','".$v['goodsid']."','".$v['goodsname']."','".$v['price']."','".$v['unit']."','".$v['logistics_price']."','".$v['weight']."','".$money."',".UID.",'$time')");
		 	}
		 	$sqladd=" INSERT INTO  ".$this->dbprefix."wx_parcellist(`listid`,`parcelid`,`pb_id`,`goodsid`,`goodsname`,`price`,`unit`,`logistics_price`,`weight`,`money`,`operationuser`,`createtime`) values ".$sqlval;
		 }
		 
		 //构建更新数据语句
		 if(count($aryupd)>0){  
		 	foreach ($aryupd as $k=>$v){
		 		$money = intval($v['number'])*$v['price'] + $v['logistics_price']*$v['weight'];
		 		$sqlupd="update ".$this->dbprefix."wx_parcellist set parcelid='$parcel',pb_id='".$v['pb_id']."',goodsid='".$v['goodsid']."',goodsname='".$v['goodsname']."',price='".$v['price']."',unit='".$v['unit']."',logistics_price='".$v['logistics_price']."',weight='".$v['weight']."',money='".$money."',operationuser='".UID."',createtime='".$time."' where listid='".$v['listid']."'";
		 		$arysqlupd[]=$sqlupd;
		 	} 
		 }
		
		 //构建删除数据语句
		 if(count($arydel)>0){
		 	$sqlval="";
		 	foreach ($arydel as $k=>$v){
		 		$sqlval.=((empty($sqlval)?"":",").$v['listid']);
		 	}
		 	if(!empty($sqlval))
		 	   $sqldel="delete ".$this->dbprefix."wx_parcellist where FIND_IN_SET(listid,'".$sqlval."')";
		 }
		 
		 $db=M("wx_parcellist");
		 $retadd=$retupd= $retdel=1; //默认是成功状态
		 
		 $db->startTrans(); //启动事务
		 
		 if($sqladd){
		    $retadd=$db->execute($sqladd);
		 } 
		 
		 if(count($arysqlupd)>0){
			 foreach ($arysqlupd as $k=>$sql){
			 	if(empty($sql))continue;
			    $retupd=$db->execute($sql);
			    //如果失败就退出循环，失败
			    if(!$retupd){
			    	break;  
			    }
			 }
		 }
		 
		 if($sqldel){
		    $retdel=$db->execute($sqldel);
		 }
		 
		 if($retadd && $retupd && $retdel){
		    $db->commit();
		    $ret=array('staute'=>'success','msg'=>"保存数据成功");
		 }
		 else {
		    $db->rollback();
		    $ret=array('staute'=>'error','msg'=>"保存数据失败");
		 }  
		$this->ajaxReturn($ret);
    }

    public function delete_wx_parcellist(){
     if(IS_GET){
        $map['listid'] = I('get.id');
        $row = D('wx_parcellist')->where($map)->delete();
        if($row != flase){
        	$this->success("删除成功") ;
        }else{
        	$this->error("删除失败") ;
        }

     }

    }
}